<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>宣讲点单</span>
      </div>
    </template>

    <div class="search-form">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="formInline.courseName" placeholder="请输入课程名称" clearable @keyup.enter="onSubmit"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.expertId" placeholder="请选择专家" clearable filterable>
            <el-option v-for="(sItem, sIndex) in expertList" :key="sIndex" :label="sItem.name" :value="sItem.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.status" placeholder="请选择订单状态" multiple collapse-tags collapse-tags-tooltip
            clearable filterable>
            <el-option label="待确认" :value="0" />
            <el-option label="已确认" :value="1" />
            <el-option label="已拒绝" :value="2" />
            <el-option label="已取消" :value="3" />
            <el-option label="待专家确认" :value="4" />
            <el-option label="待企业确认" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="formInline.auditStatus" placeholder="请选择订单审核状态" clearable filterable>
            <el-option label="待审核" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核未通过" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">
            <el-icon>
              <Search />
            </el-icon>
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="table-data" v-loading="loading">
      <el-table :data="indentData" stripe borderresizable highlight-hover-row show-overflow keep-source
        scrollbar-always-on>
        <el-table-column v-for="(tableItem, tableIndex) in indentTableColumns" :key="tableIndex" :prop="tableItem.field"
          :label="tableItem.label" :min-width="tableItem.minWidth" :formatter="tableItem.formatter"
          show-overflow-tooltip></el-table-column>

        <el-table-column fixed="right" field="opera" label="操作" min-width="150">
          <template #default="{ row }">
            <el-button type="warning" link @click="indentDetail(row)">查看</el-button>
            <el-button type="warning" link @click="indentApproval(row)"
              v-if="row.auditStatus == '0' && isFillingSystem">审核</el-button>
            <el-button type="success" link @click="indentSure(row)"
              v-if="(row.status == 0 || row.status == 4) && isFillingSystem">确认</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-page">
        <el-pagination background layout="prev, pager, next" :total="dataTotal" :page-size="pageSize"
          :current-page="currentPage" @current-change="currentChange" />
      </div>
    </div>

    <approval-dialog v-model:visible="dialogVisible" @approvalChange="approvalChange" />
  </el-card>
</template>
<script>
export default { name: 'backendPublicizeIndent' }
</script>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import approvalDialog from "@/components/backend/approval.vue"
import { http } from '@/utils/http/index';
import { dateFormatter } from "@/utils/backend.js"
import { ContentTypeEnum } from '@/enums/httpEnum';
import { useAuthStore } from '@/stores/modules/auth.js';

/* 路由 */
const route = useRouter();

/* 用户信息 */
const authStore = useAuthStore()

/* 当前用户是否为最高级的系统管理员 */
const isFillingSystem = computed(() => {
  let actions = authStore.userInfo.actions
  if (!actions) return
  const find = actions.find(item => item.id == '4')
  return find ? true : false
})

onMounted(() => {
  getExpertList()
  onSubmit()
})

/* 搜索表单 */
const formInline = ref({
  courseName: "",
  expertId: "",
  status: "",
  auditStatus: "",
})

/* 专家下拉列表请求 */
const expertList = ref([])
const expertPageIndex = ref(1)
const expertPageSize = ref(1000)
const getExpertList = () => {
  let params = {
    pageIndex: expertPageIndex.value,
    pageSize: expertPageSize.value
  }
  http.$POST(`/TheoryStudyM/GetExpertInfoList`, params).then(res => {
    expertList.value = expertList.value.concat(res.result.dataLst)
    if (res.result.countAll > res.result.pageIndex * res.result.pageSize) {
      expertPageIndex.value = expertPageIndex.value + 1
      getExpertList()
    }
  }).catch(() => {
    ElMessage.warning("查询失败")
  })
}

/* 分页 */
const dataTotal = ref(0)
const pageSize = ref(15)
const currentPage = ref(1)

if (route.currentRoute.value.query.currentPage) {
  currentPage.value = Number(route.currentRoute.value.query.currentPage)
}

/* 切换页码方法 */
const currentChange = (val) => {
  currentPage.value = val
  onSubmit()
}

/* 表格数据加载动画 */
const loading = ref(false)

/* 表格数据 */
const indentData = ref([])

/* 预约时段字段过滤数值 */
const timeTypeFormatter = (row, column, cellValue) => {
  return cellValue == 0 ? '上午' : '下午'
}

/* 预约状态字段过滤数值 */
const statusFormatter = (row, column, cellValue) => {
  if (cellValue == 0) return '待确认'
  if (cellValue == 1) return '已确认'
  if (cellValue == 2) return '已拒绝'
  if (cellValue == 3) return '已取消'
  if (cellValue == 4) return '待专家确认'
  if (cellValue == 5) return '待企业确认'
}

/* 审核状态字段过滤数值 */
const auditStatusFormatter = (row, column, cellValue) => {
  return cellValue == 0 ? '待审核' : cellValue == 1 ? '审核通过' : cellValue == 2 ? '审核未通过' : ''
}
/* 表格字段 */
const indentTableColumns = reactive([
  { field: "courseName", label: "课程名称", minWidth: "400" },
  { field: "expertName", label: "专家", minWidth: "120" },
  { field: "appointTime", label: "预约时间", minWidth: "120", formatter: dateFormatter },
  { field: "timeType", label: "预约时段", minWidth: "120", formatter: timeTypeFormatter },
  { field: "location", label: "位置", minWidth: "120" },
  { field: "listenerCount", label: "听众人数", minWidth: "120" },
  { field: "linkMan", label: "联系人", minWidth: "120" },
  { field: "linkManTel", label: "联系人电话", minWidth: "120" },
  { field: "auditStatus", label: "审核状态", minWidth: "120", formatter: auditStatusFormatter },
  { field: "status", label: "确认状态", minWidth: "120", formatter: statusFormatter },
  { field: "commingCount", label: "到场人数", minWidth: "120" },
  { field: "evaluateCount", label: "评价人数", minWidth: "120" },
  { field: "appointDescribe", label: "预约说明", minWidth: "120" },
])

/* 列表筛选 */
const onSubmit = () => {
  loading.value = true
  let params = {
    pageIndex: currentPage.value,
    pageSize: pageSize.value,
    orderbyCol: "appointTime",
  }
  let dfi = {
    Logic: 0,
    Filters: []
  }

  for (let k in formInline.value) {
    if (formInline.value[k]) {
      if (k == 'expertId' || k == 'auditStatus') {
        dfi.Filters.push({
          Field: k,
          Operator: 8,
          Value: formInline.value[k]
        })
      } else if (k == 'status') {
        /**订单状态多选 */
        if (formInline.value[k].length > 0) {
          dfi.Filters.push(...[0, 1, 2, 3, 4, 5].filter(el => !formInline.value[k].includes(el)).map(item => ({
            Field: k,
            Operator: 9,
            Value: item
          })))
          // dfi.Filters.push({
          //   Field: k,
          //   Operator: 0,
          //   Value: formInline.value[k]
          // })
        }
      } else {
        dfi.Filters.push({
          Field: k,
          Operator: 0,
          Value: formInline.value[k]
        })
      }
    }
  }

  if (dfi.Filters.length) {
    params.dfi = dfi
  }
  http.$POST("/PreachM/GetPreachOrderInfoList", params).then(res => {
    loading.value = false
    if (res.isError) return
    indentData.value = res.result.dataLst
    dataTotal.value = res.result.countAll
  }).catch(() => {
    loading.value = false
    ElMessage.warning("查询失败，请重试")
  })
}

/* 查看详情 */
const indentDetail = (row) => {
  let { href } = route.resolve({
    path: "/backend/publicize-indent/detail",
    query: { id: row.id, currentPage: currentPage.value }
  })
  window.open(href, "_blank")
}

/* 点击确认 */
const indentSure = (row) => {
  ElMessageBox.confirm(
    '是否要确认此点单',
    '请确认',
    {
      distinguishCancelAndClose: true,
      confirmButtonText: '确认',
      cancelButtonText: '拒绝',
      type: 'warning',
    }
  ).then(() => {

    sureOrder(row, 1)

  }).catch((action) => {

    console.log(action)
    if (action == 'cancel') {
      sureOrder(row, 2)
    } else {
      ElMessage.info("已取消操作")
    }

  })
}

/* 确认点单 */
const sureOrder = (row, status) => {
  /* 调用修改接口，更改状态 */
  http.$POST(`/PreachM/ConfirmPreachOrder`, {
    orderId: row.id,
    status,
    appointDescribe: '',
    // 1:专家 2: 企业
    UserType: 1
  }).then(res => {
    if (res.IsError) {
      ElMessage.warning("操作失败")
    } else {
      ElMessage.success("操作成功")
      onSubmit()
    }
  }).catch(() => {
    ElMessage.warning("操作失败")
  })
}

/* 审核弹窗 */
const dialogVisible = ref(false)

/* 当前列数据 */
const currentColumn = ref({})

/* 审核 */
const indentApproval = (row) => {
  dialogVisible.value = true
  currentColumn.value = row
}

/* 提交审核回调 */
const approvalChange = (approvalForm) => {
  console.log(approvalForm);
  let params = {}

  if (approvalForm.approval == '1') {
    params = {
      id: currentColumn.value.id,
      auditStatus: 1
    }
  } else {
    params = {
      id: currentColumn.value.id,
      auditStatus: 2
    }
  }

  changeCheckStatus(params)
}

/* 更改状态值 */
const changeCheckStatus = (params) => {
  http.$POST("/PreachM/AddOrUpdatePreachOrderInfo", { ...params }, { headers: { 'Content-Type': ContentTypeEnum.FORM_DATA } }).then(res => {
    if (res.IsError) {
      ElMessage.warning('操作失败');
    } else {
      ElMessage.success('操作成功');
      onSubmit()
    }
  }).catch(() => {
    ElMessage.warning('操作失败');
  })
}
</script>

<style lang='scss' scoped>
@import "@/assets/styles/backendElement.scss";
</style>